# Create your views here.
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.views.generic import (CreateView, UpdateView, ListView)
from accounts.forms import (UserForm, UserProfileForm)
from accounts.models import UserProfile


class LoginRequiredMixin(object):
    ''' view to login, should be first parent of a sub class '''
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs)


class UserCreateView(CreateView):
    model = User
    template_name = 'user_edit.html'
    form_class = UserForm
    def get_success_url(self):
        return reverse('contact-list')

class UserProfileView(LoginRequiredMixin, UpdateView):
    ''' update user profile '''
    model = UserProfile
    template_name= 'user_profile.html'
    form_class = UserProfileForm

    def get_object(self):
        try:
            return self.request.user.get_profile()
        except:
            profile = UserProfile()
            profile.user = self.request.user
            profile.save()
            return profile

    def get_success_url(self):
        return reverse('contact-list')

class UserContactView(LoginRequiredMixin, ListView):
    ''' list all contacts belongs to a given user '''
    template_name = 'user_contact.html'

    def get_queryset(self):
        return self.request.user.contact_set.all()

    def get_context_data(self, **kwargs):
        context = super(UserContactView, self).get_context_data(**kwargs)
        context['user'] = self.request.user
        return context


